<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
            <el-form-item label="名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="得分" prop="score">
                <InputNumberRange size="small" controls_position="right" :value="scoreRange"></InputNumberRange>
            </el-form-item>
            <el-form-item label="开始时间">
                <el-date-picker v-model="daterangeStartTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                    <el-option v-for="dict in dict.type.ex_exercise_status_dict" :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['ex:exercise:add']">创建练习</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['ex:exercise:remove']">删除</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="exerciseList" @selection-change="handleSelectionChange" :height="table_height">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="名称" align="center" prop="name" width="200">
                <template slot-scope="scope">
                    <router-link :to="'/ex/' + (scope.row.status != 3 ? 'do' : 'check') + '/index.vue/' + scope.row.id + '/'+0" class="link-type">
                        <span>{{ scope.row.name }}</span>
                    </router-link>
                </template>
            </el-table-column>
            <el-table-column label="总题数" align="center" prop="questionCount"/>
            <el-table-column label="对题数" align="center" prop="rightCount"/>
            <el-table-column label="得分" align="center" prop="score">
                <template slot-scope="scope">
                    <span v-html="scoreFormat(scope.row.score)"></span>
                </template>
            </el-table-column>
            <el-table-column label="答题用时" align="center" :formatter="second_format" prop="answerTime"/>
            <el-table-column label="开始时间" align="center" prop="startTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.startTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="结束时间" align="center" prop="endTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.endTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.ex_exercise_status_dict" :value="scope.row.status"/>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['ex:exercise:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

        <!-- 添加或修改理论练习对话框 -->
        <el-dialog title="创建理论练习" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="mini">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入名称" style="width: 260px" clearable>
                        <el-tooltip slot="append" class="item" effect="dark" content="自动生成" placement="top">
                            <el-button icon="el-icon-help" @click="generateName"></el-button>
                        </el-tooltip>
                    </el-input>
                </el-form-item>
                <el-form-item label="选题策略" prop="sig">
                    <el-radio-group v-model="form.sig">
                        <el-radio label="ratio">按题库比例</el-radio>
                        <el-radio label="average">平均选择</el-radio>
                        <el-radio label="optional">自选</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="题目数量" prop="total" v-if="form.sig !== 'optional'">
                    <el-input-number size="small" :max="questionTotal" :min="0" v-model="form.questionCount" @input="$forceUpdate()" controls-position="right"/>
                </el-form-item>
                <el-form-item label="选题策略" prop="checkeds">
                    <div class="customer-table">
                        <el-table v-loading="loading" ref="questionTable" :data="questionList" height="355" width="100%" @selection-change="handleQuestionChange" :show-header="false" size="small">
                            <el-table-column type="selection" width="45"/>
                            <el-table-column width="400">
                                <template slot-scope="scope">
                                    <el-row :gutter="10" class="mb8">
                                        <el-col :span="1.7"><dict-tag :options="dict.type.ex_question_topic_dict" :value="scope.row.topic"/></el-col>
                                        <el-col :span="1">({{scope.row.count}})</el-col>
                                    </el-row>
                                </template>
                            </el-table-column>
                            <el-table-column>
                                <template slot-scope="scope" v-if="form.sig === 'optional' && scope.isSelected">
                                    <el-input-number size="small" :min="0" :max="scope.row.count" @change="$forceUpdate" v-model="scope.row.number" controls-position="right"></el-input-number>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-popover placement="top"  trigger="hover" width="240">
                    <p>是否立即开始训练</p>
                    <div style="text-align: right; margin: 0">
                        <el-button size="mini" type="text" @click="submitForm(1)">稍后训练</el-button>
                        <el-button type="primary" size="mini" @click="submitForm(2)">立即训练</el-button>
                    </div>
                    <el-button type="primary" slot="reference">创建</el-button>
                </el-popover>
<!--                <el-button type="primary" @click="submitForm">确 定</el-button>-->
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {listExercise, delExercise, createExercise} from "@/api/ex/exercise";
import {get_question_ids_group_by_topic} from "@/api/ex/question";
import {arrSumByKey, fillNode} from "@/utils/zzDouUtils/arrayUtil";
import {parseTime} from '@/utils/ruoyi';
import {secondFormat} from '@/utils/zzDouUtils/dateUtil';
import InputNumberRange from "@/views/components/number/input-number-range.vue";

export default {
    name: "Exercise",
    dicts: ['ex_exercise_status_dict','ex_question_topic_dict'],
    components:{InputNumberRange},
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 理论练习表格数据
            exerciseList: [],
            // 是否显示弹出层
            open: false,
            // 状态时间范围
            daterangeStartTime: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                name: null,
                score: null,
                startTime: null,
                status: null,
            },
            scoreRange:[],
            // 表单参数
            form: {
                name: null,
                sig: 'ratio',
                questionCount: 0,
                checkeds:[],
                status: null,
            },
            // 表单校验
            rules: {
                name:[
                    {required: true, message: "请输入名称(可点击自动生成按钮)", trigger: "blur"},
                ],
                checkeds:[
                    { type: 'array', required: true, message: "请选择范畴", trigger: "blur" }
                ]
            },
            //题库列表
            questionList: [],
            questionTotal: null,
        };
    },
    created() {
        this.getList();
    },
    methods: {
        second_format(row, column) {
            return secondFormat(row.answerTime);
        },
        /** 查询理论练习列表 */
        getList() {
            this.loading = true;
            this.queryParams.params = {};
            let data;
            if (null != this.daterangeStartTime && '' != this.daterangeStartTime) {
                data = this.addDateRange(this.queryParams, this.daterangeStartTime,'StartTime'); //开始时间
            }
            data = this.addDateRange(this.queryParams, this.scoreRange,'Score'); //分数
            listExercise(data).then(response => {
                this.exerciseList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                name: null,
                sig: 'ratio',
                questionCount: 0,
                checkeds:[],
                status: null,
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.daterangeStartTime = [];
            this.scoreRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.getQuestionIdsGroupByTopic();
            this.reset();
            this.open = true;
        },
        /** 提交按钮 */
        submitForm(status) {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    //自定义校验
                    if (this.form.sig != 'optional'){
                        if (this.form.questionCount == 0){this.$modal.msgWarning("题目数量不可为0");return;}
                        if (this.form.checkedTotal < this.form.questionCount){this.$modal.msgWarning("题目数量超过了题库总数");return;}
                        if (this.form.sig == 'average'){//平均选择
                            let length = this.form.checkeds.length;
                            var half = this.form.questionCount % length == 0 ? this.form.questionCount / length : this.form.questionCount / length + 1;
                            for (let i = 0; i < length; i++) {
                                const item = this.form.checkeds[i];
                                if (item.count < half){
                                    this.$modal.msgWarning("超出题库数量");
                                    return;
                                }
                            }
                        }
                    }else{
                        let allCount = arrSumByKey(this.form.checkeds,'number');
                        if (allCount === 0){this.$modal.msgWarning("题目数量不可为0");return;}
                    }
                    //发送请求
                    this.form.status = status;
                    createExercise(this.form).then(response => {
                        this.$modal.msgSuccess("创建成功");
                        this.open = false;
                        this.getList();
                        if (status === 2){
                            //跳转
                            this.$tab.openPage(this.form.name, '/ex/do/index.vue/'+ response.data.id +'/' + 0, {});
                        }
                    });
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除理论练习编号为"' + ids + '"的数据项？').then(function () {
                return delExercise(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            });
        },
        //-------------------------------------------
        /** 生成测试名称 */
        generateName(){
          this.form.name = '练习_' + parseTime(new Date,'{y}/{m}/{d}_{h}:{i}:{s}');
        },
        /** 根据范畴分组获取个数 */
        getQuestionIdsGroupByTopic(){
            get_question_ids_group_by_topic().then(response =>{
                this.questionList = fillNode(response.data,'number',0);
                this.questionTotal = arrSumByKey(response.data,'count');
                this.loading = false;
            })
        },
        /** 选中题库 */
        handleQuestionChange(selection){
            this.form.checkeds = selection;
            this.form.checkedTotal = arrSumByKey(selection,'count');
        },
        /** 格式化分数 */
        scoreFormat(cellValue){
            if (cellValue === null){
                cellValue = 0;
            }
            let color = (cellValue >= 80) ? '#67C23A' : (cellValue < 80 && cellValue >= 50) ? '#E6A23C' : '#F56C6C';
            return `<span style="color: ${color};font-size: 18px;font-weight: bold;">${cellValue}</span>`
        }
    }
};
</script>
<style>
.customer-table{
    border-style: solid;
    border-color: silver;
    border-width: 1px;
    width: 620px;
    height: 360px;
}
.el-table__row>td{
    border: none;
}
.el-table::before {
    height: 0px;
}
</style>
